package com.xoa.service.crm.bidding;

import com.xoa.dao.certificate.CrmCertificateMapper;
import com.xoa.dao.crm.bidding.CrmBiddingInfoMapper;
import com.xoa.dao.crm.bidding.CrmTenderInfoMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.certificate.CrmCertificateWithBLOBs;
import com.xoa.model.crm.bidding.CrmBiddingInfoWithBLOBs;
import com.xoa.model.crm.bidding.CrmTenderInfo;
import com.xoa.model.crm.bidding.CrmTenderInfoWithBLOBs;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.users.Users;
import com.xoa.service.department.DepartmentService;
import com.xoa.service.users.UsersService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.GetAttachmentListUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class TenderInfoService {

    @Resource
    private CrmTenderInfoMapper crmTenderInfoMapper;

    @Resource
    private CrmBiddingInfoMapper biddingInfoMapper;

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private CrmCertificateMapper crmCertificateMapper;

    @Resource
    private DepartmentService departmentService;

    @Resource
    private UsersService usersService;

    /**
     * 作者 廉立深
     * 日期 2020/10/12
     * 方法介绍  查询投标项目
     * 参数 [request, tenderInfoWithBLOBs]
     * 返回 com.xoa.util.ToJson
     **/
    public ToJson getTenderInfo(HttpServletRequest request, CrmTenderInfoWithBLOBs tenderInfoWithBLOBs, Integer page, Integer limit,boolean useFlag) {
        ToJson toJson = new ToJson(1,"false");
        Map map = new HashMap();
        try {
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(limit);
            pageParams.setUseFlag(useFlag);
            map.put("pageParams",pageParams);
        }catch (Exception e){
            e.printStackTrace();
        }
        try {
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
            String sqlType = "xoa" + request.getSession().getAttribute("loginDateSouse");

            if (!StringUtils.checkNull(tenderInfoWithBLOBs.getUserId())){
                map.put("userId",users.getUserId());
            }

            map.put("tenderId",tenderInfoWithBLOBs.getTenderId());
            map.put("biddingId",tenderInfoWithBLOBs.getBiddingId());
            map.put("tenderStatus",tenderInfoWithBLOBs.getTenderStatus());
            map.put("hitStatus",tenderInfoWithBLOBs.getHitStatus());
            List<CrmTenderInfoWithBLOBs> tenderInfoList = crmTenderInfoMapper.getTenderInfo(map);
            tenderInfoList.forEach ( item -> {

                //招标信息的附加参数
                CrmBiddingInfoWithBLOBs crmBiddingInfo = item.getCrmBiddingInfo();
                if ( crmBiddingInfo != null ){

                    //采购部门
                    if (crmBiddingInfo.getPurchaseDeptid() != null){
                        crmBiddingInfo.setPurchaseDeptName(departmentService.getDpNameById(crmBiddingInfo.getPurchaseDeptid()));
                    }

                    //招标文件
                    if (!StringUtils.checkNull(crmBiddingInfo.getAttachmentName()) && !StringUtils.checkNull(crmBiddingInfo.getAttachmentId())) {
                        List<Attachment> attachmentList = GetAttachmentListUtil.returnAttachment(crmBiddingInfo.getAttachmentName(), crmBiddingInfo.getAttachmentId(), sqlType, "certification");
                        crmBiddingInfo.setAttachmentList(attachmentList);
                    }

                    //投标人
                    if (!StringUtils.checkNull(crmBiddingInfo.getTenderUserid())){
                        crmBiddingInfo.setTenderUserName(usersService.getUserNameById(crmBiddingInfo.getTenderUserid()));
                    }

                    //查看人
                    if (!StringUtils.checkNull(crmBiddingInfo.getViewUserid())){
                        crmBiddingInfo.setViewUserName(usersService.getUserNameById(crmBiddingInfo.getViewUserid()));
                    }
                }

                //投标信息附件
                if (!StringUtils.checkNull(item.getAttachmentName()) && !StringUtils.checkNull(item.getAttachmentId())) {
                    List<Attachment> attachmentList = GetAttachmentListUtil.returnAttachment(item.getAttachmentName(), item.getAttachmentId(), sqlType, "certification");
                    item.setAttachmentList(attachmentList);
                }

                //供应商
                if (!StringUtils.checkNull(item.getUserId())){
                    item.setUserName(usersService.getUserNameById(item.getUserId()));
                }


            });
            toJson.setObj(tenderInfoList);
            PageParams pageParams = (PageParams) map.get("pageParams");
            toJson.setTotleNum(pageParams.getTotal());
            toJson.setMsg("ok");
            toJson.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    /**
     * 作者 廉立深
     * 日期 2020/10/12
     * 方法介绍  编辑投标接口
     * 参数 [request, tenderInfoWithBLOBs]
     * 返回 com.xoa.util.ToJson
     **/
    public ToJson editTenderInfo(HttpServletRequest request, CrmTenderInfoWithBLOBs tenderInfoWithBLOBs,String tenderEnd) {
        ToJson toJson = new ToJson(1,"false");
        try {
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);


            if (tenderInfoWithBLOBs.getTenderId() != null){
                if( !StringUtils.checkNull(tenderEnd) && "tenderEnd".equals(tenderEnd) ){
                    tenderInfoWithBLOBs.setEndDate(new Date());
                }
                crmTenderInfoMapper.updateByPrimaryKeySelective(tenderInfoWithBLOBs);
            }else {
                tenderInfoWithBLOBs.setUserId(users.getUserId());
                crmTenderInfoMapper.insertSelective(tenderInfoWithBLOBs);
            }
            toJson.setMsg("ok");
            toJson.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }



    /**
     * 作者 陈东虎
     * 日期 2020/10/17
     * 方法介绍  查询投标项目
     * 参数 [request, tenderInfoWithBLOBs]
     * 返回 com.xoa.util.ToJson
     **/
    public ToJson getTenderByIdAndStatus(HttpServletRequest request, CrmTenderInfoWithBLOBs tenderInfoWithBLOBs) {
        ToJson toJson = new ToJson(1,"false");
        try {
            Map map = new HashMap();
            map.put("biddingId",tenderInfoWithBLOBs.getBiddingId());
            List<CrmTenderInfoWithBLOBs> tenderInfos = crmTenderInfoMapper.getTenderInfo(map);
            if(tenderInfos!=null&&tenderInfos.size()>0){
                CrmBiddingInfoWithBLOBs biddingInfoWithBLOBs = biddingInfoMapper.selectByPrimaryKey(Integer.valueOf(tenderInfoWithBLOBs.getBiddingId()));
                if(biddingInfoWithBLOBs!=null){
                    for(CrmTenderInfoWithBLOBs crmTenderInfoWithBLOBs : tenderInfos){
                        crmTenderInfoWithBLOBs.setProjectNo(biddingInfoWithBLOBs.getProjectName());
                        crmTenderInfoWithBLOBs.setProjectName(biddingInfoWithBLOBs.getProjectName());
                        if(crmTenderInfoWithBLOBs.getUserId()!=null){ //查询供应商
                            Users users = usersMapper.getUserId(crmTenderInfoWithBLOBs.getUserId());
                            if(users!=null){
                                crmTenderInfoWithBLOBs.setUserName(users.getUserName());
                            }
                        }
                        if(crmTenderInfoWithBLOBs.getTenderStatus()!=null){ //投标状态
                            if("1".equals(crmTenderInfoWithBLOBs.getTenderStatus())){
                                crmTenderInfoWithBLOBs.setTenderStatus("未查看");
                            }else if("2".equals(crmTenderInfoWithBLOBs.getTenderStatus())){
                                crmTenderInfoWithBLOBs.setTenderStatus("未完成");
                            }else if("3".equals(crmTenderInfoWithBLOBs.getTenderStatus())){
                                crmTenderInfoWithBLOBs.setTenderStatus("完成");
                            }else{
                                crmTenderInfoWithBLOBs.setTenderStatus("");
                            }
                        }else{
                            crmTenderInfoWithBLOBs.setTenderStatus("");
                        }

                        if(crmTenderInfoWithBLOBs.getHitStatus()!=null){ //中标状态
                            if("0".equals(crmTenderInfoWithBLOBs.getHitStatus())){
                                crmTenderInfoWithBLOBs.setHitStatus("待定");
                            }else if("1".equals(crmTenderInfoWithBLOBs.getHitStatus())){
                                crmTenderInfoWithBLOBs.setHitStatus("中标");
                            }else if("2".equals(crmTenderInfoWithBLOBs.getHitStatus())){
                                crmTenderInfoWithBLOBs.setHitStatus("未中标");
                            }else{
                                crmTenderInfoWithBLOBs.setHitStatus("");
                            }
                        }else{
                            crmTenderInfoWithBLOBs.setHitStatus("");
                        }
                    }
                    toJson.setData(tenderInfos);
                    toJson.setMsg("ok");
                    toJson.setFlag(0);
                }else{
                    toJson.setMsg("未找到项目信息");
                }
            }else{
                toJson.setData(new ArrayList());
                toJson.setMsg("暂无数据");
                toJson.setFlag(0);
            }
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    public ToJson getCertificate(HttpServletRequest request){
        ToJson toJson = new ToJson(1,"false");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);//获取当前登录人
        if(users!=null){
            Map map = new HashMap();
            //当前登录人
            map.put("userId",users.getUserId());
            //登陆人角色  (如果角色不是供应商  就查看  全部  如果是供应商  就只能看自己的)
            map.put("userPriv",3);//这里只能查看自己的，xml判断的是!=1才有条件这里只要不是1都可以
            List<CrmCertificateWithBLOBs> certificateList =  crmCertificateMapper.selectByCertificates(map);
            if(certificateList!=null&&certificateList.size()>0){ //已经上传过资质证书
                toJson.setTurn(true);
                toJson.setFlag(0);
            }else{
                toJson.setMsg("未上传资质证书");
                toJson.setTurn(false);
            }
        }else{
            toJson.setMsg("未知错误，请刷新页面重试");
            toJson.setTurn(false);
        }
        return toJson;
    }

    /**
     * 作者 陈东虎
     * 日期 2020/10/17
     * 方法介绍  根据biddingId和当前登录人查询投标信息
     *只返回attachmentId截成的数组，投标操作只需要操作投标文件，其他字段不需要操作，所以只对附件的增删，不进行分页
     * 参数 [request, tenderInfoWithBLOBs]
     * 返回 com.xoa.util.ToJson
     **/
    public ToJson getFileByBiddingId(HttpServletRequest request,Integer biddingId){
        ToJson toJson = new ToJson(1,"false");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);//获取当前登录人
        if(biddingId!=null){
            if(users!=null){
                Map map = new HashMap();
                map.put("biddingId",biddingId);
                map.put("userId",users.getUserId());
                List<CrmTenderInfoWithBLOBs> crmTenderInfoWithBLOBsList = crmTenderInfoMapper.getTenderInfo(map);
                if(crmTenderInfoWithBLOBsList!=null&&crmTenderInfoWithBLOBsList.size()>0){
                    CrmTenderInfoWithBLOBs crmTenderInfoWithBLOBs = crmTenderInfoWithBLOBsList.get(0); //因为一个供应商和一个招标信息只会有一个投标所以这里只取一个
                    if(crmTenderInfoWithBLOBs!=null&&!StringUtils.checkNull(crmTenderInfoWithBLOBs.getAttachmentId())){
                        String[] attIdArr = crmTenderInfoWithBLOBs.getAttachmentId().split(",");
                        String[] attNameAr = crmTenderInfoWithBLOBs.getAttachmentName().split(",");
                        List<Attachment> attachmentsList = new ArrayList<>(); //用来返回数据
                        if(attIdArr.length==attNameAr.length){ //只有id和name数组长度一样才处理
                            for(int i=0;i<attIdArr.length;i++){
                                if(!StringUtils.checkNull(attIdArr[i])&&!StringUtils.checkNull(attNameAr[i])){ //判断只有id和name都不为空
                                    Attachment attachment = new Attachment();
                                    attachment.setAttachName(attNameAr[i]);
                                    attachment.setAttachId(attIdArr[i]);
                                    attachmentsList.add(attachment);
                                }
                            }
                        }
                        if(attachmentsList.size()>0){
                            toJson.setData(attachmentsList);
                            toJson.setMsg("查询成功");
                            toJson.setFlag(0);
                        }else{
                            toJson.setData(new ArrayList());
                            toJson.setMsg("暂无数据");
                            toJson.setFlag(0);
                        }
                    }else{
                        toJson.setData(new ArrayList());
                        toJson.setMsg("暂无数据");
                        toJson.setFlag(0);
                    }
                }else{
                    toJson.setData(new ArrayList());
                    toJson.setMsg("暂无数据");
                    toJson.setFlag(0);
                }
            }else{
                toJson.setMsg("未知错误，请刷新后重试");
            }
        }else{
            toJson.setMsg("参数错误");
        }
        return toJson;
    }
}
